package cn.tedu.vrd07.filter;

import cn.tedu.vrd07.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
//urlPatterns配置需要拦截的请求地址，可配置多个地址
@WebFilter(filterName = "MyFilter",urlPatterns ={"/send.html","/admin.html","/admin-banner.html","/admin-product.html"} )
public class MyFilter implements Filter {
    //当过滤器销毁时执行的方法
    public void destroy() {
    }
    //在客户端请求到Controller之前和之后会执行的方法
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        System.out.println("执行了！");
        HttpServletRequest request= (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //得到session对象
        HttpSession session=request.getSession();
        //得到session中的用户对象
        User user= (User) session.getAttribute("user");
        if (user!=null){//登录了 放行
            chain.doFilter(req, resp);//允许执行controller执行
        }else {//未登录 拦截
            //重定向到登录页面
            response.sendRedirect("/login.html");
        }
    }
    //当过滤器初始化时执行的方法
    public void init(FilterConfig config) throws ServletException {

    }

}
